<template>
  <div class="container">
    <el-row>
      <el-col>
        <h1>welcome to use</h1>
        <el-form :rules="rules" :model="loginData" ref="checkvalid" label-position="left">
          <el-form-item label="account：" prop="username" label-width="80px">
            <el-input v-model="loginData.username" />
          </el-form-item>
          <el-form-item label="password：" prop="password" label-width="80px">
            <el-input type="password" v-model="loginData.password" />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="login">Login</el-button>
            <el-button type="primary" @click="function () { $router.push('/register') }">register</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script>

import { ElLoading } from 'element-plus'
import { ElMessageBox } from 'element-plus'
import { generateUUID } from '@/util/uuid.js'
import { loginApi } from "@/api/server";
import * as storage  from '@/util/localstorageutil.js';

export default {
  name: "LoginPage",
  data() {
    return {
      loginData: {
        username: "",
        password: "",
      },
      rules: {
        username: [
          { required: true, message: "Please enter username", trigger: "blur" },
        ],
        password: [
          { required: true, message: "Please enter password", trigger: "blur" },
        ],
        sex: [
          { required: true, message: "Please select sex", trigger: "change" },
        ],
      },
    };
  },

  methods: {
    showPasswordError(message) {
      ElMessageBox.confirm(message, "Error", {
        confirmButtonText: "OK",
        cancelButtonText: "Cancel",
        showCancelButton: false,
        type: "error",
        center: true,
      }).then(() => {
        // User clicked "OK" (confirm button).
        // You can perform additional actions here if needed.
      }).catch(() => {
        // User clicked "Cancel" or closed the dialog.
        // You can perform additional actions here if needed.
      });
    },

    saveData(token, user) {
      storage.setItem(storage.LS_TOKEN, token);
      storage.setItem(storage.LS_USERINFO, JSON.stringify(user));
      //默认使用第一个租户
      storage.setItem(storage.LS_CURRENT_TENANT,JSON.stringify(user.tenants.length>0?user.tenants[0]:null));
    },

    login() {
      // Validate the form and save the changes
      this.$refs.checkvalid.validate((valid) => {
        if (valid) {
          // Handle the save logic here (e.g., update user data)
          // After saving, close the dialog
          console.log("合法" + valid + JSON.stringify(this.loginData));
          console.log("Login data:", generateUUID());
          //loading
          const loadingInstance = ElLoading.service({ fullscreen: true })
          loginApi(this.loginData.username, this.loginData.password)
            .then((res) => res.data)
            .then((res) => {
              loadingInstance.close()
              if (res.resultCode === 0) {
                //登录成功
                console.log("login success");
                this.saveData(res.data.token, res.data);
                this.$router.push('/');
              } else {
                //失败
                this.showPasswordError(res.resultMessage);
              }
            })
            .catch(err => {
              console.log('err' + err);
            })
            .finally(()=>{
              loadingInstance.close();
            })
        } else {
          // If validation fails, do nothing (the form will display error messages)
          console.log("不合法" + valid + JSON.stringify(this.editUser));
        }
      });
    },
  },

};

</script>

<style scoped>
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  padding: 0 20px;
}

.login {
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>